<script setup >
import { ref } from "vue"
import { postFileApi } from "@/api/file"
import {getArticleApi,addArticleApi,modyfyArticleApi} from '@/api/article'
import { ElMessage } from 'element-plus'
import {useRouter,useRoute} from 'vue-router'
import upImg from "@/components/upImg.vue";
import { postStatus } from "@/utils/globleVar"
const route = useRoute()
const router = useRouter()
import {useUserStore} from '@/stores/user'
const userStore = useUserStore()

const articleId = ref()
const articleDetail = ref({})

if(route.query.articleId){
  articleId.value = parseInt(route.query.articleId) 
  getArticle(articleId.value)
}

  async function getArticle(articleId){
    const resp = await getArticleApi(articleId)
    articleDetail.value= resp.data.data

    showArticleDetail.value.title = articleDetail.value.title
    showArticleDetail.value.content = articleDetail.value.content
    showArticleDetail.value.filesUrl = articleDetail.value.images
  }

//文章信息 初值
const showArticleDetail = ref({
  title:'',
  content:'',
  filesUrl:''
})

//发布新文章的请求表单
const articleForm={
    userId: '',
    title:articleDetail.value.title,
    content:articleDetail.value.content
}

//校验规则
const articleFormRules = {
    //标题
    title:[
        {
            require:true,
            message:'标题不能为空',
            trigger:'blur'
        },
    ],
    content:[
        {
            require:true,
            message:'内容不能为空',
            trigger:'blur'
        }
    ],
    
}
const articleFormRef = ref()
 //强制刷新输入框视图 避免不能输入值
  function changeValue(e) {
    this.$forceUpdate()
  }
//返回上级url
const onBack = () => {
  router.back()
}

//新图片
const imgFile = ref(FileList)
const upFile = (imgFiles)=>{
  imgFile.value = imgFiles
}
//提交发布/更新要求
const onSubmit = async ()=>{
  //修改文章
  if(articleId.value){
    //构造请求数据
    const updateArticleForm={
      id: articleId.value,
      title:showArticleDetail.value.title,
      content:showArticleDetail.value.content,
      images:[],
      status:postStatus.draft
    }
    //处理新图片
    try{
      if(imgFile.value.length !== 0){
        const uploadPromises = imgFile.value.map((file) =>
        postFileApi(file).then((respUpImg) => ({
          post_id:articleId.value,
          image_url: respUpImg.data.data[0],
        }))
        );
        // 等待所有图片上传完成
        const newImages = await Promise.all(uploadPromises);
        newImages.forEach(img=>{
        updateArticleForm.images.push(img)
        })
      }
    }catch(e){
      ElMessage.error(e)
      console.log(e)
    }   
    //处理旧图片
    const imageUrlArr = showArticleDetail.value.filesUrl
    imageUrlArr.forEach((oldImg)=>{
      //构造图片信息
      const img = {
        post_id:articleId.value,
       image_url:oldImg.imageUrl
      }
      updateArticleForm.images.push(img)
    })
    //更新
    try{
      if(updateArticleForm.content === ''){
        ElMessage.warning('文章内容不能为空')
        return
      }
      if(updateArticleForm.title === ''){
        ElMessage.warning('文章标题不能为空')
        return
      }
      const respUpUserInfo = await modyfyArticleApi(updateArticleForm)
      if(respUpUserInfo.data.code === 200){
        router.push('/')
        ElMessage.success('更新成功，待审核')
      }
    }catch(e){
      console.log(e)
      ElMessage.error(e)
    }
    
  }else{
    //新发布文章
    try{
      articleForm.userId = userStore.userInfo.id
      articleForm.title = showArticleDetail.value.title
      articleForm.content = showArticleDetail.value.content
      if(articleForm.title === ''){
      ElMessage.warning('请输入文章标题')
      return
      }
      if(articleForm.content === ''){
        ElMessage.warning('请输入文章内容')
        return
      }
      if(imgFile.value.length === 0){
        ElMessage.warning('请上传图片')
        return
      }
      const resp = await  addArticleApi(articleForm,imgFile.value)
      if(resp.data.code === 200){
        router.push('/')
        ElMessage.success('发布成功，待审核')
      }
    }catch(e){
      console.log(e)
      ElMessage.error('更新异常，请联系管理员')
    }
  }
}
//图片列中删除已有的某个图片
const onDelImg = (id)=>{
  const imgsUrl =  articleDetail.value.images
  imgsUrl.forEach((img,index) => {
    if(img.id === id){
      imgsUrl.splice(index,1)
    }
  })
  showArticleDetail.value.filesUrl = imgsUrl
}
</script>

<template>
<div class="box">
  <div class="add">
        <!-- 导航栏 -->
        <el-page-header 
        title="返回"
        @back="onBack"
        :icon="ArrowLeftBold">
          <template #content>
            <div class="flex items-center">
              <el-avatar
                :size="32"
                class="mr-3"
                :src="userStore.userInfo.avatar"
              />
              <span 
              v-if="articleId"
              class="text-sm mr-2" 
              style="color: var(--el-text-color-regular)">
              更新文章
              </span>
              <span 
              v-else
              class="text-sm mr-2" 
              style="color: var(--el-text-color-regular)">
              发布新贴
              </span>
            </div>
          </template>
        </el-page-header>
        <!-- 标题 内容 -->
        <el-form
        ref="articleFormRef"
        :rules="articleFormRules"
        :model="articleForm"
        >
          <el-form-item prop="title">
            <el-input
            type="textarea"
            v-model="showArticleDetail.title"
            @input="changeValue"
            clearable
            placeholder="请输入标题" >
            </el-input>
          </el-form-item>
          <el-form-item prop="content">
            <el-input 
            type="textarea"
            v-model="showArticleDetail.content"
            @input="changeValue"
            clearable
            placeholder="请输入内容">
            </el-input>
          </el-form-item>
          <!-- 图片上传 -->
          <upImg
          :showConfirm="false"
          :filesUrl="showArticleDetail.filesUrl"
          @onUpload="upFile"
          @delImg="onDelImg"
          ></upImg>      
          <el-form-item>
            <el-button 
              @click="onSubmit"
              type="primary">发布</el-button>
          </el-form-item>
        </el-form>
  </div>
</div>
</template>

<style lang="scss" scoped>
::-webkit-scrollbar{
    display: none;
    background-color: aliceblue;
}
.box {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f0f0;
}

.add {
  width: 80%;
  background-color: #fff;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.flex {
  display: flex;
  align-items: center;
}

.el-page-header {
  margin-bottom: 20px;
  border-bottom: 1px solid #e5e5e5;
  padding-bottom: 10px;
}

.el-form-item {
  margin-bottom: 15px;
}

.el-input__inner {
  font-size: 14px;
}

.el-button:hover {
  background-color: #3a8ee6;
}
</style>